<?php
/**
 * Created by PhpStorm.
 * User: 李京蔚
 * Date: 2018/6/11
 * Time: 15:37
 */

namespace App\Http\Controllers\Common;


use Illuminate\Http\Request;

class Base64UploadController extends ApiController
{
    /**
     * base64上传图片
     * @param Request $request
     * @param string base64_img
     * @return mixed
     */
    public function base64Upload(Request $request)
    {
        $base64_img = $request->post('base64_img', '');

        if (empty($base64_img)) {
            return $this->setStatusCode(412)->message('请上传base64图片！');
        }
        $date_name = date("Y-m-d");
        $up_dir = './storage/uploads/' . $date_name . '/';
        create_dir($up_dir);
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
            $type = $result[2];
            if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
                $new_file = $up_dir . date('YmdHis') . uniqid() . '.' . $type;
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))) {
                    $img_url = ltrim($new_file, '.');
                    $data['url'] = $img_url;
                    return $this->success($data);
                } else {
                    return $this->failed('上传失败！');
                }
            } else {
                //文件类型错误
                return $this->setStatusCode(412)->message('图片上传类型错误！');

            }
        } else {
            //文件错误
            return $this->setStatusCode(412)->message('文件错误！');
        }
    }
}